<?php

class FormController extends PsController
{
	public function accessRules() {
		return array(
			array('allow',
			// allow all users to perform 'index' and 'view' actions
			),
		);
	}

	public function actionAttach()
	{
		$response = array();

		$propertyCaseForm = $this->loadUserModel($_POST['property_case_form_id'], 'PropertyCaseForm');
		$propertyCase = $propertyCaseForm->propertyCase;
		$pdfForm = $propertyCaseForm->pdfForm;

		// handle upload
		Yii::import("common.widgets.PsPlUpload.PsDbPlUploadHandler");
		$allowedExtensions = array('jpg', 'jpeg', 'gif', 'png', 'bmp', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt', 'csv');
		$sizeLimit = 50 * 1024 * 1024; // maximum file size in bytes
		$uploadHandler = new PsDbPlUploadHandler(Yii::app()->user->model->party_id, $allowedExtensions, $sizeLimit);

		$userUploadDir = '/Transactions/' . $propertyCase->uuid . '/Forms/' . strip_tags($pdfForm->name);
		$result = $uploadHandler->handleUpload($userUploadDir);

		if ($result == null) { // chunk uploaded
		} else { // file upload completed.
			if ($result['success'] == true) {
				$userFile = $result['userfile'];

				$supportingDocument = new SupportingDocument;
				if ($_POST['supportingDocumentName'] == '') {
					$name = $userFile->filename;
				} else {
					$name = $_POST['name'];
				}

				$supportingDocument->name = CHtml::encode($name);
				$supportingDocument->property_case_form_id = $propertyCaseForm->id;
				$supportingDocument->user_file_id = $userFile->id;
				$supportingDocument->save();

				Journal::addEntry('PropertyCase', $propertyCase->id, 'form-attach', 'Supporting Document Added'); // Record event

				$response['success'] = true;
			} else {
				$response['error'] = $result['error'];
			}
		}

		$response['error'] = $result['error'];

		print CJSON::encode($response);
	}
}
?>